/**
 *
 */
package com.wedroid.r2d2.support.response;

import java.io.IOException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.impl.client.AbstractResponseHandler;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lute
 */
public class DroidResponseHandler<T extends DroidResponse> extends AbstractResponseHandler<T> {

    private final Logger logger = LoggerFactory.getLogger(DroidResponseHandler.class);

    private Class<? extends T> responseType;

    /**
     * @param responseType
     */
    public DroidResponseHandler(Class<? extends T> responseType) {
        this.responseType = responseType;
    }

    /* (non-Javadoc)
     * @see org.apache.http.impl.client.AbstractResponseHandler#handleEntity(org.apache.http.HttpEntity)
     */
    @Override
    public T handleEntity(HttpEntity entity) throws IOException {

        String body = EntityUtils.toString(entity, Consts.UTF_8);
        logger.debug("#handleEntity - Get response body of type [{}]: {}", responseType, body);

        try {
            T t = responseType.newInstance();
            t.parse(body);
            return t;
        } catch (InstantiationException e) {
            logger.error("#handleEntity - Creating response of type [{}] encoutners InstantiationException: {}", responseType, e);
        } catch (IllegalAccessException e) {
            logger.error("#handleEntity - Creating response of type [{}] encounters IllegalAccessException: {}", responseType, e);
        }
        return null;
    }

}
